//
//  LGTForgetPasswordVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/13.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD

class LGTForgetPasswordVC: LGTBaseVC {

    var codePhoneTextField:UITextField? // 验证码手机号视图
    var codeTextField:UITextField? // 验证码视图
    var codeBtn:LGTButton? //获取验证码
    var passwordTextField:UITextField? //新密码
    var surePasswordTextField:UITextField? //确认密码
    var loginBtn:UIButton?
    var timer:Timer?
    var timeIndex:Int = 0
    var isForgetVC:Bool = true //是不是忘记密码视图
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.addNote()
    }
    
    override func setUI() {
        super.setUI()
        
        var title:String = "找回登录密码"
        if self.isForgetVC == false{
            title = "设置密码"
        }
        self.setBavBarStyle(navBarHiden: false, title: title, back: true)
        
        let phoneLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: 14, text: "+86")
        self.view.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 76)
            make.height.equalTo(KRate * 14)
            make.top.equalTo(86 * KRate + NavBarH())
        }
        
        self.codePhoneTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "仅支持中国大陆手机号", textColor: TextColor, limitCout: 11)
        self.view.addSubview(self.codePhoneTextField!)
        self.codePhoneTextField!.snp.makeConstraints { (make) in
            make.left.equalTo(phoneLabel.snp_rightMargin).offset(KRate * 22)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 160)
            make.centerY.equalTo(phoneLabel)
        }
        
        let line:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(phoneLabel.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.codeTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "请输入验证码", textColor: TextColor, limitCout: 11)
        self.view.addSubview(self.codeTextField!)
        self.codeTextField!.snp.makeConstraints { (make) in
            //make.left.equalTo(phoneLabel.snp_leftMargin)
            make.left.equalTo(KRate * 76)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 90)
            make.top.equalTo(line).offset(KRate * 20)
        }
        
        
        self.codeBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "获取验证码", font: Font_Normal_12, color: DisableColor, selectedColor: DisableColor)
        self.codeBtn?.isUserInteractionEnabled = false
        self.view.addSubview(self.codeBtn!)
        self.codeBtn?.addTarget(self, action: #selector(sendCodeAction), for: UIControl.Event.touchUpInside)
        self.codeBtn?.snp.makeConstraints({ (make) in
            make.right.equalTo(-KRate * 78)
            make.width.equalTo(KRate * 62)
            make.height.equalTo(20)
            make.centerY.equalTo(self.codeTextField!)
        })
        
        let line2:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.codeTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.passwordTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.default, placeholder: "请输入新密码", textColor: TextColor,limitCout: 20)
        self.view.addSubview(self.passwordTextField!)
        self.passwordTextField?.isSecureTextEntry = true
        
        let psLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: CGFloat(KRate * 14), text: "新密码")
        self.view.addSubview(psLabel)
        psLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 14)
           // make.top.equalTo(line2.snp_bottomMargin).offset(KRate * 20)
            make.centerY.equalTo(self.passwordTextField!)
            make.width.equalTo(KRate * 60)
        }
        
        self.passwordTextField?.snp.makeConstraints({ (make) in
            make.left.equalTo(psLabel.snp_rightMargin).offset(KRate * 14)
            make.height.equalTo(KRate * 20)
            make.top.equalTo(line2).offset(KRate * 20)
            //make.centerY.equalTo(psLabel)
            make.right.equalTo(KRate * -100)
        })
        
        let line3:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.passwordTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.surePasswordTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.default, placeholder: "请再次输入新密码", textColor: TextColor, limitCout: 11)
        self.view.addSubview(self.surePasswordTextField!)
        self.surePasswordTextField?.isSecureTextEntry = true
        
        let psLabel2:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: CGFloat(KRate * 14), text: "确认密码")
        self.view.addSubview(psLabel2)
        psLabel2.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 14)
            //make.top.equalTo(line3.snp_bottomMargin).offset(KRate * 20)
            make.centerY.equalTo(self.surePasswordTextField!)
            make.width.equalTo(KRate * 60)
        }

        self.surePasswordTextField?.snp.makeConstraints({ (make) in
            make.left.equalTo(psLabel2.snp_rightMargin).offset(KRate * 14)
            make.height.equalTo(KRate * 20)
             make.top.equalTo(line3).offset(KRate * 20)
            //make.centerY.equalTo(psLabel2)
            make.right.equalTo(KRate * -100)
        })

        let line4:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line4)
        line4.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.surePasswordTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        
        self.loginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "确认", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:CGFloat(KRate * 20))
        self.loginBtn!.backgroundColor = DisableColor
        self.loginBtn!.isUserInteractionEnabled = false
        self.view.addSubview(self.loginBtn!)
        self.loginBtn!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(KRate * -75)
            make.height.equalTo(40 * KRate)
            make.top.equalTo(line4.snp_bottomMargin).offset(KRate * 40)
        }
        
        self.loginBtn?.addTarget(self, action: #selector(loginAction), for: UIControl.Event.touchUpInside)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    func addNote(){
        self.codePhoneTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.codeTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.passwordTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.surePasswordTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
    }
    
    @objc private func textFieldChange(textField:UITextField){
        
        if self.codePhoneTextField?.text?.count == 11 && (self.codeTextField?.text?.count ?? 0 > 0) && self.passwordTextField?.text?.count ?? 0 > 0 && self.surePasswordTextField?.text?.count ?? 0 > 0{
            self.loginBtn?.backgroundColor = YellowColor
            self.loginBtn?.isUserInteractionEnabled = true
        }else{
            self.loginBtn?.backgroundColor = DisableColor
            self.loginBtn?.isUserInteractionEnabled = false
        }
        
        //验证码可点击验证
        if self.codePhoneTextField?.text?.count == 11{
            self.codeBtn?.isUserInteractionEnabled = true
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.selected)
        }else{
            self.codeBtn?.isUserInteractionEnabled = false
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.selected)
        }
    }
    
    
    @objc func sendCodeAction(){
        if self.timeIndex > 0{
            return
        }
        
        if self.codePhoneTextField?.text?.count != 11{
            WisdomHUD.showError(text: "请输入正确的手机号码")
            return
        }
        
        weak var weakSelf = self
        let params:Dictionary<String, Any> = ["phone": self.codePhoneTextField!.text ?? "",
                                              "type": 2]
        LGTHttpUtil.httpUtil.requestData(url: Send_Code_URL, param: params, showMessage: true, success: { (json) in
            let state:Int = json["state"] as! Int
            if state == 0{
                weakSelf!.timeIndex = 60
                weakSelf!.createTimer()
            }
        }) { (json) in
            
        }
    }
    
    @objc func loginAction(){
        
        self.view.endEditing(true)
        
        if self.passwordTextField?.text?.count ?? 0 < 6{
            WisdomHUD.showError(text: "请输入6~20位数字或字母的密码")
            return
        }
        
        //密码不一致
        if self.passwordTextField?.text?.count ?? 0 > 0 && self.passwordTextField?.text?.elementsEqual(self.surePasswordTextField?.text ?? "") == false{
            WisdomHUD.showError(text: "密码不一致")
            return
        }
        
        weak var weakSelf = self
        let pass:String = LGTOCBaseUtil.md5(forLower32Bite: self.passwordTextField!.text ?? "")
        let param:Dictionary<String, Any> = ["phone": self.codePhoneTextField?.text ?? "",
                                             "password": pass,
                                             "code": self.codeTextField?.text ?? ""]
        var url:String = Find_Password_URL
        if self.isForgetVC == false{
            url = Set_New_Pass_URL
        }
        self.view.isUserInteractionEnabled = false
        LGTHttpUtil.httpUtil.requestData(url: url, param: param, showMessage:true, success: { (json) in
            weakSelf?.navigationController?.popViewController(animated: true)
            UserModel.share?.is_password = 1
            weakSelf?.view.isUserInteractionEnabled = true
        }) { (json) in
            LGTViewUtil.share.loginAction(nav: weakSelf?.navigationController, json: json)
            weakSelf?.view.isUserInteractionEnabled = true
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.closeTimer()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createTimer()
    }
    
    func createTimer(){
        if self.timeIndex <= 0{
            return
        }
        
        self.timer?.invalidate()
        weak var weakSelf = self
        self.timer = Timer.init(timeInterval: 1, repeats: true, block: { (timer:Timer) in
            weakSelf?.timeIndex -= 1
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.normal)
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.selected)
            if weakSelf!.timeIndex <= 0{
                weakSelf?.closeTimer()
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.normal)
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.selected)
            }
        })
        
        RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fire()
    }
    
    func closeTimer(){
        self.timer?.invalidate()
    }
    
    deinit {
        self.closeTimer()
    }
}
